package com.code.statistics.managers;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

/**
 * http调用的相关管理类
 *
 * @author xiaoyaowang
 */
@Component
public class HttpManager {

    private static Logger log = LoggerFactory.getLogger(HttpManager.class);

    @Value("${collect.task.bot.token}")
    private String taskToken;

    private final RestTemplate restTemplate;

    public HttpManager(@Autowired RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 获取群组成员数
     *
     * @param chatId 群组唯一标识
     */
    public Integer getNewChatMemberCount(Long chatId) {
        log.info("chatId：{}", chatId);
        if (null == chatId) {
            return 0;
        }
        String uri = "https://api.telegram.org/bot" + taskToken + "/getChatMemberCount?chat_id=" + chatId;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        String strBody = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class).getBody();
        log.info("获取群组成员数响应:{}", strBody);
        if (StringUtils.isNotBlank(strBody) && strBody.startsWith("{") && strBody.endsWith("}")) {
            JSONObject jsonObject = JSONUtil.parseObj(strBody);
            if (jsonObject.containsKey("ok")) {
                Boolean ok = jsonObject.getBool("ok");
                if (ok) {
                    if (jsonObject.containsKey("result")) {
                        return jsonObject.getInt("result");
                    }

                }

            }
        }
        return 0;
    }

}
